<?php
defined('_JEXEC') or die('Restricted access');

//
// Toolkit View
//

$db =& JFactory::getDBO();

$jversion = new JVersion();
$j15 = ($jversion->RELEASE == '1.5');

jimport('joomla.application.component.helper');
$params = JComponentHelper::getParams( 'com_nspro' );
if ($j15 == true) {
  $component = JComponentHelper::getComponent( 'com_nspro' );
  $params = new JParameter( $component->params );
}

$stats_months = $params->get('stats_months', 18);

$subs = $this->subs;
$error = '';
$message = '';

include('components/com_nspro/lib.php');

if ($_POST) {
  if ($_POST["editmailsubmit"]) {

    $query = 'SELECT * FROM `#__nspro_subs` WHERE `email` = "' . mysql_escape_string($_POST["editmail"]) . '"';
    $db->setQuery($query);

    $msub = $db->loadObject();

    if ($msub) {
      header("Location: index.php?option=com_nspro&controller=nspro&task=edit&cid[]=".$msub->id);
    }
    else {
      $error = JText::_('Email not found in subscriber list');
    }
  }
  else if ($_POST["delmailsubmit"]) {

    $query = 'SELECT * FROM `#__nspro_subs` WHERE `email` = "' . mysql_escape_string($_POST["delmail"]) . '"';
    $db->setQuery($query);

    $msub = $db->loadObject();

    if ($msub) {
      $query = 'DELETE FROM `#__nspro_subs` WHERE `email` = "' . mysql_escape_string($_POST["delmail"]) . '"';
      $db->Execute($query);

      // we have to reload subscriber list
			$query = 'SELECT * FROM `#__nspro_subs` ORDER BY `id` LIMIT 0 , 3000';
			if ($_GET["special"] == 'loadallsubs') {
				$query = 'SELECT * FROM `#__nspro_subs` ORDER BY `id`';
			}
      $db->setQuery($query);
      $subs = $db->loadObjectList();

      $message = JText::_('Subscriber deleted successfully');
    }
    else {
      $error = JText::_('Email not found in subscriber list');
    }
  }
  else if ($_POST["newsletterToMail"]) {

    $query = 'SELECT * FROM `#__nspro_newsletters` WHERE `id` = "' . mysql_escape_string($_POST["newsletterIdToSend"]) . '"';
    $db->setQuery($query);

    $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

    $nsl = $db->loadObject();

    if ($nsl) {
      $mMessage = FilterNewsletterSmartText(JText::_('Friend'), $_POST["emailToSend"], $nsl->id, $nsl->message, 0);

      $query = 'SELECT * FROM `#__nspro_newsletter_attachments` WHERE `newsletter_id` = "' . mysql_escape_string($nsl->id) . '" ORDER BY `id`';
      $db->setQuery($query);
      $mattachments = $db->loadObjectList();

      $attachment = array();
      if (count($mattachments) > 0) {
        foreach( $mattachments as $mat) {
          $attachment[] = $target_dir.$mat->filename;
        }
      }

      if (MySendMailBounceHeader($nsl->fEmail, $nsl->fName, $_POST["emailToSend"], $nsl->subject, $mMessage, true, null, null, $attachment) !== true) {
        $error = JText::_('Newsletter could not be sent');
      }
      else {
        $message = JText::_('Newsletter sent successfully');
      }
    }
    else {
      $error = JText::_('Newsletter ID not found');
    }
  }
  else if ($_POST["selnewslettersend"]) {

    $query = 'SELECT * FROM `#__nspro_newsletters` WHERE `id` = "' . mysql_escape_string($_POST["newsletterIdToSend"]) . '"';
    $db->setQuery($query);

    $nsl = $db->loadObject();

    if ($nsl) {

      if (count($_POST["subscribersToSend"]) > 0) {
        $errorCount = 0;
        foreach($_POST["subscribersToSend"] as $msubId) {

          $query = 'SELECT * FROM `#__nspro_subs` WHERE `id` = "' . mysql_escape_string($msubId) . '"';
          $db->setQuery($query);

          $msub = $db->loadRow();

          if ($msub) {
            $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

            $mMessage = FilterNewsletterSmartText($msub[1], $msub[2], $nsl->id, $nsl->message, $msub[0]);

            $query = 'SELECT * FROM `#__nspro_newsletter_attachments` WHERE `newsletter_id` = "' . mysql_escape_string($nsl->id) . '" ORDER BY `id`';
            $db->setQuery($query);
            $mattachments = $db->loadObjectList();

            $attachment = array();
            if (count($mattachments) > 0) {
              foreach( $mattachments as $mat) {
                $attachment[] = $target_dir.$mat->filename;
              }
            }

            if (MySendMailBounceHeader($nsl->fEmail, $nsl->fName, $msub[2], $nsl->subject, $mMessage, true, null, null, $attachment) !== true) {
              $errorCount = $errorCount + 1;
            }
          }
          else {
            $errorCount = $errorCount + 1;
          }
        } //foreach

        if ($errorCount != 0) {
          $error = $errorCount . ' ' . JText::_('messages could not be sent');
        }
        else {
          $message = JText::_('Newsletter(s) sent successfully');
        }
      }
      else {
        $error = JText::_('No Subscribers specified');
      }
    }
    else {
      $error = JText::_('Newsletter ID not found');
    }
  }
  else if ($_POST["createsubquick"]) {
    // create quick subscriber

    $sname = mysql_escape_string($_POST["newsubname"]);
    $semail = mysql_escape_string($_POST["newsubemail"]);
    $sdate = mysql_escape_string($_POST["newsubdatetime"]);
    $sdate = date('Y-m-d H:i:s', strtotime($sdate));
    $sconf = mysql_escape_string($_POST["newsubconfirmed"]);
    $mysublists = $_POST["newsubmailing_lists2"];
    $snotes = mysql_escape_string($_POST["newsubnotes"]);

    if ((is_array($mysublists)) && (count($mysublists) > 0)) {
      $slists = implode(',', $mysublists);
    }

    $query = 'INSERT INTO `#__nspro_subs` (`name`, `email`, `datetime`, `confirmed`, `mailing_lists`, `notes`)' .
             'VALUES ("'.$sname.'", "'.$semail.'", "'.$sdate.'", "'.$sconf.'", "'.$slists.'", "'.$snotes.'")';

    $db->setQuery($query);
    if (!$db->query()) {
      $error = JText::_('Failed to create New Subscriber');
    }
    else {
      $message = JText::_('New Subscriber created successfully');
    }
  }
  else if ($_POST["assigntomailinglist"]) {

    $query = 'SELECT * FROM `#__nspro_lists` WHERE `published` = "1" and `id` = "' . mysql_escape_string($_POST["mailinglisttoassignto"]) . '"';
    $db->setQuery($query);

    $mylist = $db->loadObject();

    if ($mylist) {

      if (count($_POST["subscribersToAssign"]) > 0) {
        $errorCount = 0;
        foreach($_POST["subscribersToAssign"] as $msubId) {

          $query = 'SELECT * FROM `#__nspro_subs` WHERE `id` = "' . mysql_escape_string($msubId) . '"';
          $db->setQuery($query);

          $msub = $db->loadObject();

          if ($msub) {

            $found = false;
            $suboldlists = explode(',', $msub->mailing_lists);
            $subnewlists = '';
            foreach ($suboldlists as $mslist) {
              if ($mslist == $mylist->id) {
                $found = true;
                break;
              }
              else {
                if ($subnewlists == '') {
                  $subnewlists = $mslist;
                }
                else {
                  $subnewlists = $subnewlists . ',' . $mslist;
                }
              }
            }

            if ($found != true) {
              if ($subnewlists == '') {
                $subnewlists = $mylist->id;
              }
              else {
                $subnewlists = $subnewlists . ',' . $mylist->id;
              }
              $query = 'UPDATE `#__nspro_subs` SET `mailing_lists` = "' . mysql_escape_string($subnewlists) . '" WHERE `id` = "' . mysql_escape_string($msub->id) . '"';
              $db->setQuery($query);
              $db->query();
            }
            // else continue
          }
          else {
            $errorCount = $errorCount + 1;
          }
        } //foreach

        if ($errorCount != 0) {
          $error = $errorCount . ' ' . JText::_('subscribers could not be assigned');
        }
        else {
          $message = JText::_('Mailing List assigned successfully');
        }
      }
      else {
        $error = JText::_('No Subscribers specified');
      }
    }
    else {
      $error = JText::_('Mailing List ID not found');
    }

  }
}


if ($message != '') {
  print '<dl id="system-message"><dt class="message">Message</dt><dd class="message message fade"><ul><li>';
  print $message;
  print '</li></ul></dd></dl>';
}

if ($error != '') {
  print '<dl id="system-message"><dt class="error">Error</dt><dd class="message error fade"><ul><li>';
  print $error;
  print '</li></ul></dd></dl>';
}

jimport('joomla.html.pane');

$mtabs =& JPane::getInstance('tabs');

print $mtabs->startPane('toolkittabs');
print $mtabs->startPanel('Tools', 'toolkittabtools');

include('tools.php');

print $mtabs->endPanel();
print $mtabs->startPanel('Statistics', 'toolkittabstats');

include('statistics.php');

print $mtabs->endPanel();
//print $mtabs->startPanel('Parameters', 'toolkittabparams');

//include('parameters.php');

//print $mtabs->endPanel();
print $mtabs->endPane();

?>
<center><small><i>NS Pro by <a href="http://www.mavrosxristoforos.com/">Mavrosxristoforos.com</a> Copyright 2009-2011</i></small></center>